package com.iemes.service.impl.workcenter_model;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.ItemBomFormMap;
import com.iemes.entity.ItemBomRelationFormMap;
import com.iemes.entity.ItemFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.UDefinedDataValueFormMap;
import com.iemes.entity.WorkCenterFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.CommonService;
import com.iemes.service.workcenter_model.ItemBomService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ItemBomServiceImpl implements ItemBomService {
	@Inject
	private BaseMapper baseMapper;
	
	@Inject
	private CommonService commonService;
	
	private Logger log = Logger.getLogger(this.getClass());

	@Override
	@Transactional
	public void saveItemBom(ItemBomFormMap itemBomFormMap) throws BusinessException {
		try {			
			String id = itemBomFormMap.getStr("id");
			String itemBomNo = itemBomFormMap.getStr("item_bom_no");
			String version = itemBomFormMap.getStr("item_bom_version");
			
			if(StringUtils.isEmpty(itemBomNo)) {
				throw new BusinessException("物料BOM编号不能为空，请输入！");
			}	
			if(StringUtils.isEmpty(version)) {
				throw new BusinessException("物料BOM版本号不能为空，请输入！");
			}
			
			ItemBomFormMap itemBomFormMap2 = new ItemBomFormMap();
			itemBomFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			itemBomFormMap2.put("item_bom_no", itemBomNo);
			itemBomFormMap2.put("item_bom_version", version);
			List<ItemBomFormMap> listItemBomFormMap = baseMapper.findByNames(itemBomFormMap2);
			
			//如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(listItemBomFormMap)) {
				//更新 
				ItemBomFormMap itemBomFormMap3 = new ItemBomFormMap();
				itemBomFormMap3 = listItemBomFormMap.get(0);
				id = itemBomFormMap3.getStr("id");
				itemBomFormMap.set("id", id);
				
				baseMapper.editEntity(itemBomFormMap);
			}else {
				//新增
				id = UUIDUtils.getUUID();
				itemBomFormMap.set("id", id);
				baseMapper.addEntity(itemBomFormMap);
			}

			// 2.添加或更新子物料信息
			ItemBomRelationFormMap itemBomRelationFormMap = new ItemBomRelationFormMap();
			itemBomRelationFormMap.put("item_bom_id", id);
			baseMapper.deleteByNames(itemBomRelationFormMap);
			List<String> listItemHadAddedInBom = new ArrayList<>();
			String childItemsata = itemBomFormMap.getStr("childItems_data");
			if (!StringUtils.isEmpty(childItemsata)) {
				JSONArray jsonArray = JSONArray.fromObject(childItemsata);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject objectRow = jsonArray.getJSONObject(i);
					JSONObject objectItemSeqCell = objectRow.getJSONObject("item_seq");
					JSONObject objectItemIdCell = objectRow.getJSONObject("item_id");
					JSONObject objectUseNumCell = objectRow.getJSONObject("use_num");
					/*JSONObject objectBalanceUpCell = objectRow.getJSONObject("balance_up");
					JSONObject objectBalanceDownCell = objectRow.getJSONObject("balance_down");*/

					String itemSeqCell = objectItemSeqCell.getString("value");
					JSONArray itemSeqCellArray = JSONArray.fromObject(itemSeqCell);
					String itemSeq = itemSeqCellArray.get(0).toString();
					
					String itemIdCell = objectItemIdCell.getString("value");
					JSONArray itemIdCellArray = JSONArray.fromObject(itemIdCell);
					String itemNo = itemIdCellArray.get(0).toString();
					String itemId = itemIdCellArray.get(1).toString();
					
					String useNumCell = objectUseNumCell.getString("value");
					JSONArray useNumCellArray = JSONArray.fromObject(useNumCell);
					int useNum = Integer.valueOf(useNumCellArray.get(0).toString());
					
					/*String balanceUpCell = objectBalanceUpCell.getString("value");
					JSONArray balanceUpCellArray = JSONArray.fromObject(balanceUpCell);
					int balanceUp = Integer.valueOf(balanceUpCellArray.get(0).toString());*/
					
					/*String balanceDownCell = objectBalanceDownCell.getString("value");
					JSONArray balanceDownCellArray = JSONArray.fromObject(balanceDownCell);
					int balanceDown = Integer.valueOf(balanceDownCellArray.get(0).toString());*/

					String itemBomId = id;

					if (listItemHadAddedInBom.contains(itemId)) {
						throw new BusinessException("物料：" + itemNo + "不允许重复添加！");
					}

					itemBomRelationFormMap.put("id", UUIDUtils.getUUID());
					itemBomRelationFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
					itemBomRelationFormMap.put("item_bom_id", itemBomId);
					itemBomRelationFormMap.put("item_id", itemId);
					itemBomRelationFormMap.put("item_seq", itemSeq);
					itemBomRelationFormMap.put("use_number", useNum);
					/*itemBomRelationFormMap.put("balance_up", balanceUp);
					itemBomRelationFormMap.put("balance_down", balanceDown);*/
					itemBomRelationFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
					itemBomRelationFormMap.put("create_time", DateUtils.getStringDateTime());

					baseMapper.addEntity(itemBomRelationFormMap);

					listItemHadAddedInBom.add(itemId);
				}
			}

			// 3.添加或更新自定义数据信息
			String dataValue = itemBomFormMap.getStr("udefined_data");
			commonService.saveUDefinedDataValueS(id, dataValue);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("物料清单保存失败！" + e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delItemBom(String itemBomId) throws BusinessException {
		try {
			//1.如果物料清单被主物料绑定了，则不允许删除
			ItemFormMap itemFormMap = new ItemFormMap();
			itemFormMap.put("bom_no", itemBomId);
			List<ItemFormMap> listItemFormMap = baseMapper.findByNames(itemFormMap);
			if (ListUtils.isNotNull(listItemFormMap)) {
				String bindItemNo = "";
				for(int i=0;i<listItemFormMap.size();i++) {
					ItemFormMap map = listItemFormMap.get(i);
					if(StringUtils.isEmpty(bindItemNo)) {
						bindItemNo = map.getStr("item_no");
					}else {
						bindItemNo += "," + map.getStr("item_no");
					}
				}
				throw new BusinessException("此物料清单绑定了物料 " + bindItemNo + "，无法执行删除！");
			}
			
			// 2.删除物料清单表
			ItemBomFormMap itemBomFormMap = new ItemBomFormMap();
			itemBomFormMap.put("id", itemBomId);
			baseMapper.deleteByNames(itemBomFormMap);
			
			//3.删除物料清单关系表				
			ItemBomRelationFormMap itemBomRelationFormMap = new ItemBomRelationFormMap();
			itemBomRelationFormMap.put("item_bom_id", itemBomId);
			baseMapper.deleteByNames(itemBomRelationFormMap);
			
			//4.删除自定义数据表
			 UDefinedDataValueFormMap uDefinedDataValueFormMap = new UDefinedDataValueFormMap();
			 uDefinedDataValueFormMap.put("data_type_detail_id",itemBomId);
			 baseMapper.deleteByNames(uDefinedDataValueFormMap);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("物料清单删除失败！" + e.getMessage());
		}
	}

}
